package controllers

import (
	"baokaobang/datasourse"
	"baokaobang/models"
	"baokaobang/utils"
	"fmt"
	"github.com/kataras/iris/v12"
)

type Major struct {
	Ctx iris.Context
}

// 获取所有专业列表
func (c *Major) PostAll() interface{} {
	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	oneList := make([]models.MajorCategory, 0)
	err = db.Where("parent_id = ? and category_type = ?", 0, 1).Find(&oneList)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("获取专业列表失败：%s", err.Error()), "")
	}

	twoList := make([]models.MajorCategory, 0)
	err = db.Where("parent_id = ? and category_type = ?", 0, 2).Find(&twoList)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("获取专业列表失败：%s", err.Error()), "")
	}

	for i, item := range oneList {
		childList := make([]models.MajorCategory, 0)
		db.Where("parent_id = ?", item.Id).Find(&childList)
		oneList[i].Children = childList
		for j, category := range childList {
			majorList := make([]models.Major, 0)
			db.Where("category_id = ?", category.Id).Find(&majorList)
			oneList[i].Children[j].MajorList = majorList
		}
	}

	for i, item := range twoList {
		childList := make([]models.MajorCategory, 0)
		db.Where("parent_id = ?", item.Id).Find(&childList)
		twoList[i].Children = childList
		for j, category := range childList {
			majorList := make([]models.Major, 0)
			db.Where("category_id = ?", category.Id).Find(&majorList)
			twoList[i].Children[j].MajorList = majorList
		}
	}

	data := map[string]interface{}{
		"oneList": oneList,
		"twoList": twoList,
	}

	return utils.CommonRes(20000, "成功获取专业列表", data)
}

// 获取每个专业详情
func (c *Major) PostDetail() interface{} {
	id := c.Ctx.PostValue("id")

	if len(id) <= 0 {
		return utils.CommonRes(1000, "请提供专业id", "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库:%s", err.Error()), "")
	}

	major := new(models.MajorObj)
	ok, err := db.Table(new(Major)).Alias("m").
		Where("m.id = ?", id).
		Join("INNER", []string{"major_category", "mc"}, "m.category_id = mc.id").
		Get(major)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("专业信息获取失败:%s", err.Error()), "")
	}
	if !ok {
		return utils.CommonRes(1000, "专业信息获取失败", "")
	}

	major.MajorCategory.CategoryTypeShow = models.MajorCategoryType[major.MajorCategory.CategoryType]

	return utils.CommonRes(20000, "专业信息获取成功", major)
}
